import { BaseService, CoolCommException } from "@cool-midway/core";
import { Inject, Provide } from "@midwayjs/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { ScheduleStatus, TransportScheduleEntity } from "../entity/schedule";
import { CapacityEntity } from "../entity/capacity";
import { Context } from "@midwayjs/koa";
import { AssertScheduleDTO } from "../dto/schedule";
import { Utils } from "../../../comm/utils";
import { ProviderProfileService } from "../../provider/service/profile";
import { ProviderTeamEntity } from "../../provider/entity/team";
import * as moment from 'moment';

@Provide()
export class TransportScheduleService extends BaseService {

    @InjectEntityModel(TransportScheduleEntity)
    transportScheduleEntity: Repository<TransportScheduleEntity>

    @InjectEntityModel(CapacityEntity)
    capacityModel: Repository<CapacityEntity>

    @InjectEntityModel(ProviderTeamEntity)
    providerTeamModel: Repository<ProviderTeamEntity>

    @Inject()
    ctx: Context

    @Inject()
    utils: Utils

    @Inject()
    profileService: ProviderProfileService


    /**
     * 新增排班记录
     * @param dto 排班DTO
     * @returns 
     */
    async set(dto: AssertScheduleDTO) {
        const { capacityId, dateList, source } = dto;
        const providerId = this.ctx.provider.id;

        // 获取当前服务人员信息
        const profile = await this.profileService.getProfile(providerId);
        if (!profile?.capacityId) {
            throw new CoolCommException('请完善基础信息后进行操作');
        }

        // 确定目标运力ID
        const targetCapId = capacityId || profile.capacityId;

        // 获取目标运力信息
        const targetCapacity = await this.capacityModel.findOne({ where: { id: targetCapId } });
        if (!targetCapacity) {
            throw new CoolCommException('运力不存在');
        }

        // 权限校验：如果是修改他人的运力，必须是该运力所属团队的队长
        if (targetCapId !== profile.capacityId) {
            if (!targetCapacity.teamId) {
                throw new CoolCommException('无权操作该运力');
            }
            const team = await this.providerTeamModel.findOne({ where: { id: targetCapacity.teamId } });
            if (!team || team.ownerProviderId !== providerId) {
                throw new CoolCommException('无权操作该运力');
            }
        }

        // 校验日期列表
        if (!Array.isArray(dateList) || dateList.length === 0) {
            throw new CoolCommException('日期列表不能为空');
        }
        // 归一化为“天”（去重，后者覆盖前者）
        const dayToItem = new Map<string, { date: Date; status: number; remark: string }>();
        for (const item of dateList) {
            const m = moment(item.date);
            if (!m.isValid()) {
                throw new CoolCommException('存在非法日期');
            }
            const key = m.startOf('day').format('YYYY-MM-DD');
            dayToItem.set(key, {
                date: m.toDate(),
                status: item.status,
                remark: item.remark ?? ''
            });
        }

        // 按天处理：UNKNOWN 则删除该天记录，否则覆盖该天记录
        const saved: TransportScheduleEntity[] = [];
        for (const v of Array.from(dayToItem.values())) {
            if (v.status === ScheduleStatus.UNKNOWN) {
                await this.transportScheduleEntity.delete({ capacityId: targetCapId, date: v.date });
                continue;
            }
            // 覆盖该日期：先删后插，避免重复
            await this.transportScheduleEntity.delete({ capacityId: targetCapId, date: v.date });
            const record = await this.transportScheduleEntity.save({
                capacityId: targetCapId,
                date: v.date,
                status: v.status,
                remark: v.remark,
                source
            } as any);
            saved.push(record);
        }

        return saved;
    }

    /**
     * 根据运力ID获取排班记录
     * @param capacityId 运力ID
     * @returns 
     */
    async byCapacityId(capacityId: number): Promise<TransportScheduleEntity[]> {
        return this.transportScheduleEntity.find({ where: { capacityId } });
    }

    /**
     * 根据服务人员ID获取排班记录
     * @returns 
     */
    async byCurrentProvider(): Promise<TransportScheduleEntity[]> {
        const profile = await this.profileService.getProfile(this.ctx.provider.id);
        if (!profile) {
            throw new CoolCommException('请完善基础信息后进行操作');
        }
        return this.transportScheduleEntity.find({ where: { capacityId: profile.capacityId } });
    }
    
    /**
     * 清除运力下的所有排班记录
     * @param capacityId 运力ID
     * @returns 
     */
    async clearByCapacityId(capacityId: number): Promise<void> {
        await this.transportScheduleEntity.delete({ capacityId });
    }

    /**
     * 清除服务人员下的所有排班记录
     * @returns 
     */
    async clearByProviderId(): Promise<void> {
        const profile = await this.profileService.getProfile(this.ctx.provider.id);
        if (!profile) {
            throw new CoolCommException('请完善基础信息后进行操作');
        }
        await this.transportScheduleEntity.delete({ capacityId: profile.capacityId });
    }

}